<template>
  <!-- 顶部导航栏 -->
  <PageHeader />

  <div class="page">
    <div class="page-container">
      <!-- 自定义 Tab 导航 -->
      <div class="custom-tab-header">
        <button
            v-for="tab in tabs"
            :key="tab.key"
            class="tab-item"
            :class="{ active: activeTab === tab.key }"
            @click="switchTab(tab.key)"
        >
          <span>{{ tab.label }}</span>
        </button>
      </div>

      <!-- Tab 内容区 -->
      <div class="tab-content">
        <!-- 我发布的问题 -->
        <div v-show="activeTab === 'published'" class="tab-pane">
          <div v-if="loading.published" class="loading-state">加载中...</div>

          <div v-else-if="publishedQuestions.list.length === 0" class="empty-state">
            暂无问题记录
          </div>

          <div v-else class="list-container">
            <div
                v-for="item in publishedQuestions.list"
                :key="item.id"
                class="list-item card"
                @click="openDetail(item)"
            >
              <h3 class="title">{{ item.title }}</h3>

              <div class="meta">
                <span :class="['type-tag', getTypeTagClass(item.type)]">
                  {{ getTypeLabel(item.type) }}
                </span>
                <span :class="['status-tag', getStatusTagClass(item.status)]">
                  {{ getStatusText(item.status) }}
                </span>
                <span class="date">{{ formatDate(item.createdAt) }}</span>
              </div>

              <div class="actions">
                <button
                    v-if="['pending_review', 'rejected', 'waiting'].includes(item.status)"
                    class="btn btn-sm btn-primary"
                    @click.stop="editQuestion(item)"
                >
                  修改
                </button>
                <button
                    v-if="item.status === 'in_progress'"
                    class="btn btn-sm btn-success"
                    @click.stop="resolveQuestion(item)"
                >
                  结题
                </button>
                <button
                    class="btn btn-sm btn-danger"
                    @click.stop="deleteQuestion(item)"
                >
                  删除
                </button>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="publishedQuestions.total > pageSize" class="pagination-wrapper">
            <el-pagination
                background
                layout="prev, pager, next"
                :total="publishedQuestions.total"
                :page-size="pageSize"
                v-model:current-page="currentPage.published"
                @current-change="loadPublished"
            />
          </div>
        </div>

        <!-- 我处理的问题 -->
        <div v-show="activeTab === 'assigned'" class="tab-pane">
          <div v-if="loading.assigned" class="loading-state">加载中...</div>

          <div v-else-if="assignedQuestions.list.length === 0" class="empty-state">
            暂无待处理任务
          </div>

          <div v-else class="list-container">
            <div
                v-for="item in assignedQuestions.list"
                :key="item.id"
                class="list-item card"
                @click="openDetail(item)"
            >
              <h3 class="title">{{ item.title }}</h3>

              <div class="meta">
                <span :class="['type-tag', 'tag-success']">
                  {{ item.requester }}
                </span>
                <span :class="['status-tag', getStatusTagClass2(item.status)]">
                  {{ getStatusText2(item.status) }}
                </span>
                <span class="date">{{ formatDate(item.createdAt) }}</span>
              </div>

              <div class="actions">
                <button
                    v-if="item.status === 'waiting'"
                    class="btn btn-sm btn-success"
                    @click.stop="acceptTask(item)"
                >
                  接受
                </button>
                <button
                    v-if="item.status === 'waiting'"
                    class="btn btn-sm btn-danger"
                    @click.stop="rejectTask(item)"
                >
                  拒绝
                </button>
                <button
                    v-if="item.status === 'in_progress'"
                    class="btn btn-sm btn-primary"
                    @click="openDetail(item)"
                >
                  交流
                </button>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="assignedQuestions.total > pageSize" class="pagination-wrapper">
            <el-pagination
                background
                layout="prev, pager, next"
                :total="assignedQuestions.total"
                :page-size="pageSize"
                v-model:current-page="currentPage.assigned"
                @current-change="loadHandled"
            />
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 弹窗组件 -->
  <QuestionDetailDialog ref="detailDialogRef"/>
  <EditQuestionDialog ref="editDialogRef" @submitted="refreshList"/>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import QuestionDetailDialog from '@/components/QuestionDetailDialog.vue'
import EditQuestionDialog from '@/components/EditQuestionDialog.vue'
import PageHeader from "@/components/PageHeader.vue"
import request from '@/utils/request'
import { useRouter, useRoute } from 'vue-router'

// 当前激活的 Tab
const activeTab = ref('published')

// Tab 配置
const tabs = [
  { key: 'published', label: '我发布的问题' },
  { key: 'assigned', label: '我处理的问题' }
]

// 分页设置
const pageSize = 10
const currentPage = reactive({
  published: 1,
  assigned: 1
})

// 加载状态
const loading = reactive({
  published: false,
  assigned: false
})

// 数据存储
const publishedQuestions = reactive({ list: [], total: 0 })
const assignedQuestions = reactive({ list: [], total: 0 })

// 类型映射
const typeMap = {}

async function loadTags() {
  const res = await request.get(`/api/tag/listAll`)
  if (res.data) {
    for (let i = 0; i < res.data.length; i++) {
      typeMap[res.data[i].id + ""] = res.data[i].name
    }
  }
}

const getTypeLabel = (val) => typeMap[val] || '其他'
const getTypeTagClass = (val) => ({
  "1": 'tag-green',
  "2": 'tag-blue',
  "3": 'tag-yellow',
  "4": 'tag-red',
  "5": 'tag-purple',
  "6": 'tag-orange',
})[val] || 'tag-gray'

// 状态文本映射
const statusTextMap = {
  pending_review: '待审核',
  rejected: '被驳回',
  waiting: '等待接单',
  awaiting_admin: '等待管理员干预',
  in_progress: '处理中',
  resolved: '已解决',
}
const statusTextMap2 = { waiting: '待响应', in_progress: '处理中', resolved: '已解决' }

const getStatusText = (val) => statusTextMap[val] || val
const getStatusText2 = (val) => statusTextMap2[val] || val

const getStatusTagClass = (val) => ({
  pending_review: 'tag-info',
  rejected: 'tag-danger',
  waiting: 'tag-warning',
  awaiting_admin: 'tag-warning',
  in_progress: 'tag-primary',
  resolved: 'tag-success'
})[val] || 'tag-default'

const getStatusTagClass2 = (val) => ({
  waiting: 'tag-warning',
  in_progress: 'tag-primary',
  resolved: 'tag-success'
})[val] || 'tag-default'

// 时间格式化
const formatDate = (isoStr) => {
  return new Date(isoStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const route = useRoute()
const router = useRouter()

// 切换 Tab
const switchTab = (tabKey) => {
  activeTab.value = tabKey

  // 更新地址栏参数，不触发刷新
  const query = { ...route.query, tab: tabKey }
  router.replace({ query })

  // 加载数据
  if (tabKey === 'published') {
    loadPublished()
  } else if (tabKey === 'assigned') {
    loadHandled()
  }
}

// 加载 “我发布的问题”
const loadPublished = async () => {
  loading.published = true
  try {
    const res = await request.get('/api/questions/my/published', {
      params: { current: currentPage.published, size: pageSize }
    })
    publishedQuestions.list = res.data.records
    publishedQuestions.total = res.data.total
  } catch (err) {
    // ElMessage.error('获取发布的问题失败')
  } finally {
    loading.published = false
  }
}

// 加载 “我处理的问题”
const loadHandled = async () => {
  loading.assigned = true
  try {
    const res = await request.get('/api/questions/my/handled', {
      params: { current: currentPage.assigned, size: pageSize }
    })
    assignedQuestions.list = res.data.records
    assignedQuestions.total = res.data.total
  } catch (err) {
    // ElMessage.error('获取处理的问题失败')
  } finally {
    loading.assigned = false
  }
}

// 添加：解析查询参数
const getQueryParams = () => {
  const params = new URLSearchParams(window.location.hash.split('?')[1]);
  return {
    tab: params.get('tab')
  }
}

onMounted(() => {
  const { tab } = getQueryParams()
  if (tab === 'published' || tab === 'assigned') {
    activeTab.value = tab
  }

  setTimeout(() => {
    if (activeTab.value === 'published') loadPublished()
    else loadHandled()
  }, 50)

  loadTags()
})

// === 功能方法 ===
const detailDialogRef = ref()
const openDetail = (row) => {
  detailDialogRef.value.open(row)
}

const editDialogRef = ref()
const editQuestion = (row) => {
  if (!['pending_review', 'rejected', 'waiting'].includes(row.status)) {
    ElMessageBox.alert('该问题已进入处理流程，无法修改。', '提示', { type: 'warning' })
    return
  }
  editDialogRef.value.open(row)
}

const resolveQuestion = (row) => {
  ElMessageBox.confirm(`确认结题：“${row.title}”？`, '问题结题', { type: 'warning' }).then(async () => {
    try {
      await request.patch(`/api/questions/${row.id}/resolve`)
      ElMessage.success('结题成功')
      await loadPublished()
    } catch (err) {
      // ElMessage.error('结题失败')
    }
  }).catch(() => {})
}

const refreshList = () => {
  loadPublished()
}

const deleteQuestion = (row) => {
  ElMessageBox.confirm(`确认删除问题：“${row.title}”？`, '删除问题', { type: 'warning' }).then(async () => {
    try {
      await request.delete(`/api/questions/${row.id}`)
      ElMessage.success('删除成功')
      await loadPublished()
    } catch (err) {
      // ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const acceptTask = async (row) => {
  ElMessageBox.confirm(`确认接受问题：“${row.title}”？一旦接受，其他人将无法接单。`, '确认接单', { type: 'success' }).then(async () => {
    try {
      await request.patch(`/api/questions/${row.id}/accept`)
      ElMessage.success('任务已接受，即将进入沟通阶段')
      await loadHandled()
    } catch (err) {
      // ElMessage.error('接单失败，请稍后重试')
    }
  }).catch(() => {})
}

const rejectTask = (row) => {
  ElMessageBox.prompt('请输入拒绝理由（可选）', '拒绝任务', {
    inputPlaceholder: '例如：时间冲突、非职责范围等'
  }).then(async ({ value }) => {
    try {
      await request.patch(`/api/questions/${row.id}/reject`)
      ElMessage.info(`已拒绝任务${value ? '，理由：' + value : ''}`)
      await loadHandled()
    } catch (err) {
      // ElMessage.error('拒绝失败')
    }
  }).catch(() => {})
}
</script>

<style scoped>
.page {
  min-height: calc(100vh - 70px);
  max-height: calc(100vh - 70px);
  background-color: var(--bg);
  padding: 40px 20px;
  display: flex;
  justify-content: center;
  overflow-y: auto;
}

.page::-webkit-scrollbar {
  width: 0.5rem;
}

.page::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 0.5rem;
}

.page::-webkit-scrollbar-thumb {
  background: #3498db;
  border-radius: 0.5rem;
}

.page::-webkit-scrollbar-thumb:hover {
  background: #2980b9;
}

.page-container {
  width: 100%;
  max-width: 960px;
}

/* 自定义 Tab Header */
.custom-tab-header {
  display: flex;
  border-bottom: 1px solid var(--border);
  margin-bottom: 24px;
  font-size: 16px;
}

.tab-item {
  padding: 12px 20px;
  background: none;
  border: none;
  color: var(--text-light);
  cursor: pointer;
  position: relative;
  font-weight: 500;
  transition: all 0.2s ease;
}

.tab-item:hover {
  color: var(--primary);
}

.tab-item.active {
  color: var(--primary);
  font-weight: 600;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: var(--primary);
  border-radius: 2px;
}

/* Tab 内容区 */
.tab-content {
  min-height: 400px;
}

.tab-pane {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 列表容器 */
.list-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 列表项 */
.list-item {
  background: var(--card-bg);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 20px;
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
  cursor: pointer;
}

.list-item:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow);
  border-color: #cbd5e1;
}

.list-item .title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text);
  margin: 0 0 12px;
  line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 16px;
  font-size: 14px;
  color: var(--text-muted);
}

/* 标签样式 */
.type-tag,
.status-tag {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

/* 类型标签颜色 */
.tag-blue { background: #eff6ff; color: #1d4ed8; }
.tag-green { background: #ecfdf5; color: #059669; }
.tag-yellow { background: #fffbeb; color: #d97706; }
.tag-red { background: #fee2e2; color: #dc2626; }
.tag-purple { background: #f3e8ff; color: #7c3aed; }
.tag-orange { background: #fff7ed; color: #c2410c; }
.tag-gray { background: #f1f5f9; color: #64748b; }

/* 状态标签颜色 */
.tag-primary { background: #dbeafe; color: #1d4ed8; }
.tag-success { background: #dcfce7; color: #16a34a; }
.tag-warning { background: #fef3c7; color: #d97706; }
.tag-danger { background: #fecaca; color: #dc2626; }
.tag-info { background: #e0f2fe; color: #0369a1; }
.tag-default { background: #f1f5f9; color: #64748b; }

.date {
  margin-left: auto;
}

.text-muted {
  color: var(--text-light);
}

/* 操作按钮 */
.actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.btn {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-primary {
  background: var(--primary);
  color: white;
}

.btn-primary:hover {
  background: var(--primary-hover);
}

.btn-success {
  background: #16a34a;
  color: white;
}

.btn-success:hover {
  background: #15803d;
}

.btn-danger {
  background: #dc2626;
  color: white;
}

.btn-danger:hover {
  background: #b91c1c;
}

/* 状态提示 */
.loading-state,
.empty-state {
  text-align: center;
  padding: 60px 0;
  color: var(--text-muted);
  font-size: 15px;
}

/* 分页 */
.pagination-wrapper {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 响应式 */
@media (max-width: 768px) {
  .page-container {
    padding: 0 16px;
  }

  .meta {
    flex-direction: column;
    gap: 6px;
  }

  .date {
    margin-left: 0 !important;
  }

  .actions {
    flex-wrap: wrap;
  }

  .btn {
    flex: 1;
    min-width: 70px;
  }
}
</style>
